//
//  RecommendViewController.m
//  hunba
//
//  Created by 孙智慧 on 16/1/4.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "RecommendViewController.h"
#import "MusicPlayController.h"
#import "MyTableViewCell.h"
#import "MoreCell.h"
#import "AppDelegate.h"
#import "ZYMusicTool.h"
#import "ZYMusic.h"
#import "MusicListController.h"

@implementation RecommendViewController

#pragma mark view将要显示事件
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //控制正在播放的文字的显示效果
    if([self musicPlay].isRoationing)
    {
        self.marqueeView.musicName= [self musicPlay].playingMusic.name;
        
        [self.marqueeView startM];
    }
    else
    {
        [self.marqueeView stopM];
    }
}

#pragma mark banner 获取后处理
-(void) opSuccessForGet:(id)data
{
    operation= nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *dataParse  = [dataStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
    
    if ([[dataParse objectForKey:@"result"] isEqualToString:@"1"])
    {
        
        NSArray *arrayData=[dataParse objectForKey:@"data"];
        
        [_viewScrollView loadData:arrayData];
        
    }

}

#pragma mark 图片点击事件
-(void) buttonpress1:(UITapGestureRecognizer *)sender
{
    NSInteger albumID = sender.view.tag;
    
    MusicListController *viewController= [self.storyboard instantiateViewControllerWithIdentifier:@"MusicList"];
    
    [viewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    
    viewController->albumID=albumID;
    
    [self.view.window.rootViewController presentViewController:viewController animated:true completion:nil];
}

#pragma mark 专辑 获取后处理
-(void) opSuccessForGetZhuanJi:(id)data
{
    operation=nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *dataParse  = [dataStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
    
    if ([[dataParse objectForKey:@"result"] isEqualToString:@"1"]) {
        
        NSArray *arrayData=[dataParse objectForKey:@"data"];
        
        dispatch_async(dispatch_get_main_queue(), ^(void){
            
            [self.secondScrollView removeAllSubviews];
            
        });
        
        for (NSInteger i=0; i<[arrayData count]; i++)
        {
            NSDictionary *dict= [arrayData objectAtIndex:i];
            
            NSString *albumID= [dict objectForKey:@"id"];
            
            //NSString *Title= [dict objectForKey:@"Title"];
            
            NSString *CoverPath= [dict objectForKey:@"CoverPath"];
            
            NSString *CoverName= [dict objectForKey:@"CoverName"];
            
            UIImageView *imageView=[[UIImageView alloc] init];
            
            imageView.tag=  [ albumID intValue];
            
            imageView.contentMode= UIViewContentModeScaleAspectFit;
            
            imageView.translatesAutoresizingMaskIntoConstraints=NO;
            
            imageView.userInteractionEnabled = YES;
            
            UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonpress1:)];
            
            [imageView addGestureRecognizer:singleTap1];
            
            [Common downLoadImageByURL:imageView andURL:CoverPath andName:CoverName];
            
            dispatch_async(dispatch_get_main_queue(), ^(void){//异步加载图
                
                [self.secondScrollView addSubview:imageView];
                
                if (i==0) {
                    //ImageView左侧与父视图左侧对齐
                    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.secondScrollView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
                    [self.secondScrollView addConstraint:leftConstraint];
                }
                
                //ImageView顶部与父视图顶部对齐
                NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.secondScrollView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f];
                
                //ImageView底部与父视图顶部对齐
                NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.secondScrollView attribute:NSLayoutAttributeBottom multiplier:1.0f constant:5.0f];
                
                //ImageView高度为父视图高度
                NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:70.0f];
                
                //ImageView宽度为父视图宽度
                NSLayoutConstraint* widthConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:70.0f];
                //iOS 6.0或者7.0调用addConstraints
                [self.secondScrollView addConstraints:@[bottomConstraint, topConstraint,heightConstraint,widthConstraint]];
                
                if(i>0)
                {
                    //从第二个视图开始和第一个间距5
                    UIImageView *imageView1=(UIImageView * ) self.secondScrollView.subviews[i-1];
                    NSLayoutConstraint *spaceConstraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:imageView1 attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:5.0f];
                    [self.secondScrollView addConstraint:spaceConstraint];
                }
                
                if(i==dataParse.count-1)
                {
                    //imageView 右边距和父视图对齐 以便确定父视图的内容边界
                    UIImageView *imageView1=(UIImageView * ) self.secondScrollView.subviews[dataParse.count-1];
                    NSLayoutConstraint *Constraint = [NSLayoutConstraint constraintWithItem:imageView1 attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.secondScrollView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-5.0f];
                    [self.secondScrollView addConstraints:@[ Constraint ]];
                }
            });
        }
    }
}


#pragma mark 加载幻灯片
-(void) loadSlide
{
    operation= [[NetWorkOperation alloc] initWithDelegate:self];
    
    NSString *URL= [FxGlobal getServiceUrl:@"Recommend" andFuncName:@"slide"];
    
    NSDictionary * dictInfo = @{@"url":URL};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:1];
}

#pragma mark 加载专辑
-(void) loadZhuanji
{
    operation= [[NetWorkOperation alloc] initWithDelegate:self];
    
    NSString *URL= [FxGlobal getServiceUrl:@"Recommend" andFuncName:@"HotAlbum"];
    
    NSDictionary * dictInfo = @{@"url":URL};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:2];
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidLoad
{
 
    [super viewDidLoad];
    
    _array=[[NSMutableArray alloc]init];
    
    self.myTableView.separatorStyle= UITableViewCellSeparatorStyleNone;
    
    //设置表数据源
    self.myTableView.delegate=self;
    
    self.myTableView.dataSource=self;
 
    self.secondScrollView.delegate=self;
 
    [self setSecScrollViewContent:NO];
    
    //显示表数据
    [self setTableData];
    
    RegisterNotify(NofifyMusicPlay, @selector(stopNavBtnRoation));
    
    if(IsiPhone6P)
    {
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:self.viewScrollView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:168.0f];
        
        [self.contentView addConstraint:heightConstraint];
    }
    else if(IsiPhone6)
    {
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:self.viewScrollView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:152.0f];
        
        [self.contentView addConstraint:heightConstraint];
    }
    else{
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:self.viewScrollView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:130.0f];
        
        [self.contentView addConstraint:heightConstraint];
    }
    [_viewScrollView layoutUI];
    
    [self loadSlide];
}

#pragma mark 停止文字滚动
-(void) stopNavBtnRoation
{
    [self stopNavRightBtnRoation];
    
    [self.marqueeView stopM];
    
}

#pragma mark get请求处理
-(void) opSuccessForGet:(id)data andFlag:(NSInteger)flag
{
    if(flag==1)
    {
        [self opSuccessForGet:data]; //banner
    }
    else if(flag==2)
    {
        //专辑
        [self opSuccessForGetZhuanJi:data];
    }
    else
    {
        operation= nil;
        //热播单曲
        [_array removeAllObjects];
        
        NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSDictionary *data2 = [dataStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
        
        if ([[data2 objectForKey:@"result"] isEqualToString:@"1"])
        {
            NSArray *arrayData= [data2 objectForKey:@"data"];
            
            for (NSInteger i=0; i<arrayData.count; i++)
            {
                
                NSDictionary *dict= [arrayData objectAtIndex:i];
                
                [_array addObject:dict];
            }
        }

        [self.myTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    }
    
}

#pragma mark 设置表格的数据
-(void) setTableData
{
    operation= [[NetWorkOperation alloc] initWithDelegate:self];
    
    NSString *url= [FxGlobal getServiceUrl:@"recommend" andFuncName:@"HotMusic"];
    
    NSDictionary *dictInfo = @{@"url":url};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:0];
}

#pragma mark 设置表格有几个数据区域
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark 设置表格的行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row= indexPath.row;
    
    NSInteger count= _array.count;
    
    CGFloat r= row<count?55:44;
    
    return r;
}

#pragma mark 设置表格有几行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _hasNextPage?_array.count+1:_array.count;
}

#pragma mark 表格绑定数据
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 次方法是在拖动表格时 单元格显示在表格的bounds 范围内时触发
    if (indexPath.row < _array.count) {
        
        NSString *idefine = @"MyTableViewCell";
        
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idefine];
        
        if (cell==nil)
        {
            cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idefine];
        }
        
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        
        NSInteger i=  indexPath.row;
        
        NSDictionary *musicInfo= [_array objectAtIndex:i];
        
        cell.musicInfo = musicInfo;
        
        cell.lblMusicAuthor.text = [musicInfo objectForKey:@"NickName"];
        
        cell.lblMusic.text = [musicInfo objectForKey:@"MusicName"];
        
        cell.musicID= [musicInfo objectForKey:@"MusicID"];
        
        NSString *iconName= [musicInfo objectForKey:@"IconName"];
        
        NSString *imgPath= [musicInfo objectForKey:@"Icon"];
        
        [Common downLoadImageByURL:cell.imgMusic andURL:imgPath andName:iconName];
    
        return cell;
        
    }
    else
    {
        
        NSString  *cellIdentifier = @"NewsMoreCell";
        
        MoreCell *cell = (MoreCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (cell == nil) {
            
            NSArray* Objects = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:tableView options:nil];
            
            cell = [Objects objectAtIndex:0];
            
        }
        
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        
        return cell;
        
        
    }
}

#pragma mark 歌曲列表点击事件
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyTableViewCell *cell = (MyTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    if(![[ZYMusicTool playingMusic].filename isEqualToString:[cell.musicInfo objectForKey:@"MusicName"]])
    {
        [ZYMusicTool playingMusic].playing=NO;
        
        //获取新的歌曲
        ZYMusic *currMusic=[[ZYMusic alloc]init];
        
        currMusic.name= [cell.musicInfo objectForKey:@"MusicName"];
        
        currMusic.icon= [cell.musicInfo objectForKey:@"Icon"];
        
        currMusic.iconName= [cell.musicInfo objectForKey:@"IconName"];
        
        currMusic.musicListArray=[cell.musicInfo objectForKey:@"musiclist"];
        
        currMusic.lrcname=@"";
        
        currMusic.singer=[cell.musicInfo objectForKey:@"singer"];
        
        currMusic.djID=[cell.musicInfo objectForKey:@"ID"];
        
        currMusic.singerIcon=[cell.musicInfo objectForKey:@"singericon"];
        
        currMusic.musicID =[cell.musicInfo objectForKey:@"MusicID"];
        
        currMusic.playing = YES;
        
        currMusic.shareURL=[cell.musicInfo objectForKey:@"shareURL"];
        
        [ZYMusicTool setPlayingMusic:currMusic];
        
        [_db addViewResourse:currMusic];
        
        [self addViewRes:currMusic];
        
    }
    
    [self musicPlay].playMode=@"one";
    
    [self.view.window.rootViewController presentViewController:[self musicPlay] animated:true completion:nil];
}

#pragma mark 获取专辑
-(void) setSecScrollViewContent:(BOOL) isPageScroll
{
    self.secondScrollView.pagingEnabled=isPageScroll;
    
    [self.secondScrollView setShowsHorizontalScrollIndicator:NO];
    
    [self loadZhuanji];
    
}

#pragma mark 设置滚动视图的位置
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    CGPoint targetOffset = [self nearestTargetOffsetForOffset:*targetContentOffset];
    
    targetContentOffset->x = targetOffset.x;
    
    targetContentOffset->y = targetOffset.y;
}

#pragma mark 计算滚动视图的点
-(CGPoint) nearestTargetOffsetForOffset:(CGPoint) offset
{
    CGFloat pageSize = 75.0;
    
    NSInteger page = roundf(offset.x / pageSize);
    
    CGFloat targetX = pageSize * page;
    
    return CGPointMake(targetX, offset.y);
}

@end
